<template>
  <div ref="containerRef">
    <slot></slot>
    <Teleport to="body">
      <!-- <Transition
        @beforeEnter="handleBeforeEnter"
        @enter="handleEnter"
        @afterEnter="handleAfterEnter"
      > -->
        <div
          class="context-menu"
          v-if="showMenu"
          :style="{
            left: pos.posX + 'px',
            top: pos.posY + 'px',
          }"
          v-size-ob:content-box="handleSizeChange"
        >
          <div class="menu-list">
            <div
              class="menu-item"
              @click="handleClick(item)"
              v-for="item in menu"
              :key="item.label"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
      <!-- </Transition> -->
    </Teleport>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import useContextMenu from "./useContextMenu";
import useViewport from "./useViewport";
import vSizeOb from "./sizeDirect";
const props = defineProps({
  menu: {
    type: Array,
    default: () => [],
  },
});
const menu = computed(() => {
  return props.menu;
});
const containerRef = ref(null);
const emit = defineEmits(["select"]);

const { x, y, showMenu } = useContextMenu(containerRef);
const w = ref(0);
const h = ref(0);
function handleSizeChange({ width, height }) {
  w.value = width;
  h.value = height;
}
// 因为加了动画，这个hooks会执行很多次
const { vw, vh } = useViewport();
const pos = computed(() => {
  let posX = x.value;
  let posY = y.value;
  // x坐标
  if (x.value > vw.value - w.value) {
    posX = posX - w.value;
  }
  // y坐标
  if (y.value > vh.value - h.value) {
    posY = posY - (y.value - (vh.value - h.value));
  }
  return {
    posX,
    posY,
  };
});

function handleClick(item) {
  console.log(item);
  showMenu.value = false;
  emit("select", item);
}

function handleBeforeEnter(el) {
  el.style.height = 0;
}

function handleEnter(el) {
  el.style.height = "auto";
  const height = el.clientHeight;
  el.style.height = 0;
  // 强制回流
  // el.clientHeight
  // el.style.height = height + "px";
  // el.style.transition = "0.5s";
  requestAnimationFrame(() => {
    el.style.height = height + "px";
    el.style.transition = "0.5s";
  });
}

function handleAfterEnter(el) {
  el.style.transition = "none";
}
</script>

<style lang="scss" scoped>
.context-menu {
  position: fixed;
  background: #eee;
  box-sizing: 1px 1px 2px rgba(0, 0, 0, 0.2), 1px 1px 5px rgba(0, 0, 0, 0.2);
  min-width: 100px;
  border-radius: 5px;
  font-size: 12px;
  color: #1d1d1f;
  line-height: 1.8;
  white-space: nowrap;
  overflow: hidden;
}
.menu-list {
  padding: 0px 10px;
}
.menu-item {
  cursor: pointer;
}
.v-enter-from {
  // opacity: 0;
}
.v-enter-to {
  // transition: 0.5s;
  // opacity: 1;
}
</style>
